from PyQt5.QtCore import QThread, pyqtSignal
from core.connectors.db_connector import DatabaseConnector


class TableMatchWorker(QThread):
    """
    工作线程，用于异步匹配数据库表。
    """
    progress_signal = pyqtSignal(str)  # 阶段信息信号
    match_done_signal = pyqtSignal(list)  # 匹配完成信号，发送匹配结果

    def __init__(self, db_connector, keyword, match_mode, parent=None):
        super().__init__(parent)
        self.db_connector = db_connector
        self.keyword = keyword
        self.match_mode = match_mode
        self.is_running = True

    def isRunning(self):
        return self.is_running

    def run(self):
        """匹配表的后台处理"""
        try:
            self.progress_signal.emit(f"开始连接数据库 ({self.db_connector.get_connector_name()})")

            tables_info = self.db_connector.get_tables_info()
            self.progress_signal.emit("获取表信息成功，正在过滤匹配的表...")

            # 根据匹配模式过滤
            if self.match_mode == "前缀匹配":
                filtered_tables = [info for info in tables_info if info[0].startswith(self.keyword)]
            elif self.match_mode == "后缀匹配":
                filtered_tables = [info for info in tables_info if info[0].endswith(self.keyword)]
            else:  # 模糊匹配
                filtered_tables = [info for info in tables_info if self.keyword in info[0]]

            self.progress_signal.emit(f"匹配完成，共找到 {len(filtered_tables)} 张表。")
            self.match_done_signal.emit(filtered_tables)
        except Exception as e:
            self.progress_signal.emit(f"匹配表失败：{e}")

    def stop(self):
        """停止线程"""
        self.is_running = False
